<template>
  <div class="block">
    <px-table
      ref="tableRef"
      :data="tableData"
      :max-height="maxHeight ? maxHeight : '400px'"
      class="inspect-table"
      size="small"
      :border="noBorder ? false : true"
      :row-key="rowKey ? rowKey : 'id'"
      :header-cell-class-name="allSelectDisable"
      @select="handleSelectionChange"
      @select-all="handleSelectionChange"
    >
      <template v-for="(item, index) in tableColumns" :key="index">
        <px-table-column
          v-if="item.prop === 'selection'"
          :align="item.align ? item.align : 'center'"
          type="selection"
          :min-width="item.minWidth"
          :width="item.width"
        />
        <px-table-column
          v-else-if="item.prop === 'drag'"
          :align="item.align ? item.align : 'center'"
          :min-width="item.minWidth"
          :width="item.width"
          :fixed="item.fixed ? item.fixed : 'left'"
        >
          <px-icon><ViewList /></px-icon>
        </px-table-column>
        <px-table-column
          v-else-if="item.prop === 'index'"
          type="index"
          :label="item.label"
          :align="item.align ? item.align : 'center'"
          :min-width="item.minWidth"
          :width="item.width"
          :fixed="item.fixed ? item.fixed : 'left'"
        />
        <px-table-column
          v-else-if="item.prop === 'expend'"
          :align="item.align ? item.align : 'center'"
          type="expand"
          :min-width="item.minWidth"
          :width="item.width"
          :fixed="item.fixed"
        >
          <template v-slot="props">
            <template v-if="props.row['templateContentDTOList'] && props.row['templateContentDTOList'].length > 0">
              <div v-for="item in props.row['templateContentDTOList']" :key="item.id" class="p-[10px] inspect-table_body">
                <div class="inspect-table__title">{{ item.inspectItemContent }}（{{ item.inspectItemTypeDesc }}）</div>
                <InspectRulesTable
                  v-model:query-params="queryParams"
                  :total="0"
                  :tableColumns="getTableColumn(item, props.row.inspectContentType)"
                  :inspectContentType="props.row.inspectContentType"
                  :table-data="(item['contentItemDTOList'] as any[]) || []"
                />
              </div>
            </template>
          </template>
        </px-table-column>
        <px-table-column
          v-else-if="item.prop === 'inspectContentRangeCodeDesc,inspectContentRangeValue'"
          :label="item.label"
          :min-width="item.minWidth"
          :width="item.width"
          :align="item.align ? item.align : 'left'"
          :show-overflow-tooltip="item.showOverflowTooltip"
          :fixed="item.fixed"
        >
          <template #default="scope">{{ dealRangeVal(scope.row, item.prop) }}</template>
        </px-table-column>
        <px-table-column
          v-else-if="item.prop === 'operate'"
          :label="item.label"
          :min-width="item.minWidth"
          :width="item.width"
          :align="item.align ? item.align : 'right'"
          :show-overflow-tooltip="item.showOverflowTooltip"
          :fixed="item.fixed"
        >
          <template #default="scope">
            <px-button link type="danger" :icon="Delete" @click="itemDelete(scope.row)" />
          </template>
        </px-table-column>
        <px-table-column
          v-else
          :label="item.label"
          :min-width="item.minWidth"
          :width="item.width"
          :align="item.align ? item.align : 'left'"
          :show-overflow-tooltip="item.showOverflowTooltip"
          :fixed="item.fixed"
        >
          <template v-if="item.type === 'link'" #default="scope">
            <span style="color: #3b82f6; cursor: pointer" @click="item.customFun && item.customFun(scope.row.id)">{{
              scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-"
            }}</span>
          </template>
          <template v-else-if="item.prop === 'eqpStatusList'" #default="scope">
            {{ renderStatusDesc(scope.row.eqpStatusList) }}
          </template>
          <template v-else-if="item.customFun" #default="scope">{{ item.customFun(scope.row[item.prop]) }}</template>
          <template v-else #default="scope">
            {{ scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-" }}</template
          >
        </px-table-column>
      </template>
    </px-table>
    <pagination
      v-if="queryParams"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      class="inspection-pagination"
      :total="total"
      @pagination="queryTable"
    />
  </div>
</template>
<script setup lang="ts">
import { cloneDeep } from "@pureadmin/utils";
import { Delete } from "@px-ui/icons-vue";
import Sortable from "sortablejs";
import { nextTick, ref, watch } from "vue";
import { TableItem } from "../../types";

defineOptions({
  name: "InspectRulesTable"
});

const tableRef = ref();

const emits = defineEmits(["queryTable", "resetTable", "selectItems", "del", "onDrag"]);
const meterReadingTableColumnsDefault = ref<TableItem[]>([
  { prop: "index", label: "序号", width: "50", fixed: "left" },
  { prop: "meterReadingModeDesc", label: "抄表方式", showOverflowTooltip: true, fixed: "left" },
  { prop: "meterReadingItem", label: "抄表项", showOverflowTooltip: true, fixed: "left" },
  { prop: "unit", label: "单位", minWidth: "60", showOverflowTooltip: true },
  { prop: "maxValue", label: "最大值", minWidth: "100" },
  { prop: "minValue", label: "最小值", minWidth: "100" }
  // { prop: "eqpName", label: "设备", minWidth: "100" },
  // { prop: "autoMeterReadingPoint", label: "自动抄表点", minWidth: "100" }
]);
const judgeTableColumnsDefaultOfEqp = ref<TableItem[]>([
  { prop: "index", label: "序号", width: "50", fixed: "left" },
  { prop: "eqpStatusList", label: "适用设备状态", showOverflowTooltip: true, width: "200", fixed: "left" },
  { prop: "inspectItem", label: "巡检项", showOverflowTooltip: true, width: "200", fixed: "left" },
  { prop: "inspectContent", label: "巡检内容", showOverflowTooltip: true },
  { prop: "inspectContentRangeCodeDesc,inspectContentRangeValue", label: "内容范围", minWidth: "100", showOverflowTooltip: true }
]);
const judgeTableColumnsDefaultOfEnv = ref<TableItem[]>([
  { prop: "index", label: "序号", width: "50", fixed: "left" },
  { prop: "inspectItem", label: "巡检项", showOverflowTooltip: true, width: "200", fixed: "left" },
  { prop: "inspectContent", label: "巡检内容", showOverflowTooltip: true },
  { prop: "inspectContentRangeCodeDesc,inspectContentRangeValue", label: "内容范围", minWidth: "100", showOverflowTooltip: true }
]);
const props = defineProps<{
  tableColumns?: TableItem[];
  tableData: any[];
  childrenTableColumns?: TableItem[];
  total?: number;
  rowKey?: string;
  maxHeight?: string;
  hasDrag?: boolean;
  noBorder?: boolean;
  childrenKey?: string;
  childrenTableKey?: string;
  multiple?: boolean;
  inspectContentType?: number;
}>();

const queryParams = defineModel<{ pageNum: number; pageSize: number; value?: string; temCodeOrName?: string }>("queryParams");
function queryTable() {
  emits("queryTable", queryParams.value);
}
const getTableColumn = (item, inspectContentType) => {
  if (item.inspectItemType === 1) {
    return meterReadingTableColumnsDefault.value;
  } else {
    if (inspectContentType === 1) {
      return judgeTableColumnsDefaultOfEqp.value;
    } else {
      return judgeTableColumnsDefaultOfEnv.value;
    }
  }
};
const renderStatusDesc = data => {
  if (data) {
    return data.map(item => item.name).join("/");
  } else {
    return "-";
  }
};
function dealRangeVal(row, prop) {
  const [inspectContentRangeCodeDesc, inspectContentRangeValue] = prop.split(",");
  return `【${row[inspectContentRangeCodeDesc]}】   ${row[inspectContentRangeValue] ? row[inspectContentRangeValue] : ""}`;
}
function handleSelectionChange(val, row) {
  if (props.multiple) {
    return emits("selectItems", cloneDeep(val));
  }
  // 2、单选
  if (val.length > 1) {
    tableRef.value.clearSelection();
    tableRef.value.toggleRowSelection(row, true);
    return emits("selectItems", cloneDeep(row));
  } else {
    return emits("selectItems", cloneDeep(row));
  }
}
function itemDelete(row) {
  emits("del", row);
}
// 样式上隐藏全选
const allSelectDisable = ({ columnIndex }) => {
  if (columnIndex === 0 && !props.multiple) {
    return "allSelectDisable";
  }
};
// 表格行拖拽移动
const rowDrag = () => {
  nextTick(() => {
    const el = tableRef?.value?.$el.querySelector("tbody");
    if (el) {
      Sortable.create(el, {
        animation: 180,
        delay: 0,
        onEnd: evt => {
          emits("onDrag", evt);
        }
      });
    }
  });
};
watch(
  () => props.tableData,
  () => {
    if (props.hasDrag && props.tableData?.length > 0) {
      rowDrag();
    }
  },
  {
    immediate: true
  }
);
</script>
<style lang="scss" scoped>
.inspect-form {
  margin-bottom: 8px;

  :deep(.px-form-item) {
    width: 100%;
    margin-bottom: 8px;

    .px-input {
      width: 100%;
    }

    .px-select {
      width: 100%;
    }

    .px-select-v2 {
      width: 100%;
    }
  }

  :deep(.px-button + .px-button) {
    margin-left: 8px;
  }
}

.inspect-table-btn {
  display: flex;
  align-items: center;
  margin-bottom: 8px;

  :deep(.px-button + .px-button) {
    margin-left: 0;
  }
}

.inspect-table {
  --px-table-border-color: #dfdfdf;

  font-size: 14px;

  .inspect-table_body {
    background-color: #f5f5f5;
  }
  :deep(.px-table__header) {
    thead {
      tr {
        background-color: #e7eefb !important;

        th {
          font-size: 14px;
          font-weight: bold;
          color: #000;
          background-color: #e7eefb !important;
        }
      }
    }
  }
  :deep(.allSelectDisable .cell) {
    visibility: hidden;
  }
  :deep(.px-table__cell) {
    padding: 0;
    height: 36px;
    line-height: 36px;
    .cell {
      height: 36px;
      line-height: 36px;
    }
  }
  &__title {
    margin-bottom: 8px;
    font-size: 14px;
    font-weight: 700;
    line-height: 22px;
    color: #000;

    &::before {
      display: inline-block;
      width: 3px;
      height: 16px;
      margin-right: 6px;
      vertical-align: middle;
      content: "";
      background: #3b82f6;
      border-radius: 0 100px 100px 0;
    }
  }
}

:deep(.pagination-container) {
  height: 34px;
  padding: 0 !important;
  margin: 16px 0;
}

.inspect-table-pagination {
  position: absolute;
  right: 8px;
  bottom: 0;
}
</style>
